package com.my.storage.interceptor;

import com.my.storage.exception.TokenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author hangwen
 * @date 2023/8/15
 */
public class LoginContextInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginContextInterceptor.class);
    private static final String MANAGER_TOKEN = "iammanager";

    @Override
    public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
                                final Exception ex) throws Exception {
    }

    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
                           final ModelAndView modelAndView) throws Exception {
    }

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        //获取请求头
        String token = request.getHeader("Access-Token");
        logger.info("token:{}", token);
        //对于拿到的token进行判断，匹配就可以继续，不匹配就报错
        if (!Objects.equals(token, MANAGER_TOKEN)) {
            throw new TokenException("token 错误");
        }

        return true;
    }
}
